package config

import (
	"io"
	"os"

	yaml "gopkg.in/yaml.v2"
)

var (
	HomePath string //home 目录
)

//初始化home目录
func InitHome(homePath string) {
	HomePath = homePath

	//创建home目录
	if ok, err := PathExists(HomePath); err != nil || !ok {
		os.MkdirAll(HomePath, 0777)
	}
	//配置目录
	if ok, err := PathExists(HomePath + "/config"); err != nil || !ok {
		os.MkdirAll(HomePath+"/config", 0777)
	}
	//jobs目录
	if ok, err := PathExists(HomePath + "/jobs"); err != nil || !ok {
		os.MkdirAll(HomePath+"/jobs", 0777)
	}

	//用户配置文件
	if ok, err := PathExists(HomePath + "/config/users.yml"); err != nil || !ok {
		content := make(map[string]interface{})
		users := [](map[string]string){map[string]string{"user": "admin", "password": "admin123", "group": "AdminGroup"}, map[string]string{"user": "guest", "password": "123456", "group": "UsersGroup"}}
		content["users"] = users
		f, err1 := os.Create(HomePath + "/config/users.yml") //创建文件
		if err1 == nil {
			d, _ := yaml.Marshal(content)
			io.WriteString(f, string(d)) //写入文件(字符串)
		}
		defer f.Close()
	}

	//全局工具配置文件
	if ok, err := PathExists(HomePath + "/config/globaltool.yml"); err != nil || !ok {
		content := make(map[string]interface{})

		//jdk配置列表
		jdks := [](map[string]string){}
		content["Jdks"] = jdks
		//maven配置列表
		mavens := [](map[string]string){}
		content["Mavens"] = mavens
		//sonar配置列表
		SonarScanners := [](map[string]string){}
		content["SonarScanners"] = SonarScanners
		//gradle配置列表
		gradles := [](map[string]string){}
		content["Gradles"] = gradles

		//git配置列表
		gits := [](map[string]string){}
		content["Gits"] = gits

		//svn配置列表
		svns := [](map[string]string){}
		content["Svns"] = svns
		//写入
		f, err1 := os.Create(HomePath + "/config/globaltool.yml") //创建文件
		if err1 == nil {
			d, _ := yaml.Marshal(content)
			io.WriteString(f, string(d)) //写入文件(字符串)
		}
		defer f.Close()
	}

}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
